package com.warski.wonderfires.dlna.parser;


import com.warski.wonderfires.utils.Logger;
import org.fourthline.cling.binding.staging.MutableService;
import org.fourthline.cling.binding.xml.DescriptorBindingException;
import org.fourthline.cling.binding.xml.UDA10ServiceDescriptorBinderSAXImpl;
import org.fourthline.cling.model.ValidationException;
import org.fourthline.cling.model.meta.Service;
import org.seamless.xml.SAXParser;
import org.xml.sax.InputSource;

import java.io.StringReader;

/**
 * Created by xuhaiping on 2020/9/2.
 */
public class DLNAUDA10ServiceDescriptorBinderSAXImpl extends UDA10ServiceDescriptorBinderSAXImpl {

    @Override
    public <S extends Service> S describe(S undescribedService, String descriptorXml) throws DescriptorBindingException, ValidationException {
        if (descriptorXml == null || descriptorXml.length() == 0) {
            throw new DescriptorBindingException("Null or empty descriptor");
        }
        try {
            Logger.info("Reading service from XML descriptor, content : %s", descriptorXml);
            SAXParser parser = new DLNASAXParser();
            MutableService descriptor = new MutableService();
            hydrateBasic(descriptor, undescribedService);
            new RootHandler(descriptor, parser);
            parser.parse(new InputSource(new StringReader(descriptorXml.trim())));
            return (S) descriptor.build(undescribedService.getDevice());
        } catch (ValidationException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new DescriptorBindingException("Could not parse service descriptor: " + ex.toString(), ex);
        }
    }
}
